package com.net.xpay.common.service.impl.notification;

import com.net.xpay.common.domain.notification.Notification;
import com.net.xpay.common.enums.notification.NotificationStatus;
import com.net.xpay.common.model.FetchNotificationModel;
import com.net.xpay.common.service.notification.NotificationService;
import com.net.xpay.common.validator.NotificationValidator;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import com.net.xpay.common.manager.notification.NotificationManager;
import com.net.xpay.common.manager.notification.ReadNotificationManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private NotificationManager notificationManager;

    @Autowired
    private ReadNotificationManager readNotificationManager;

    @Autowired
    private NotificationValidator notificationValidator;

    @Override
    public Notification fetchOneByModule(Long userId, FetchNotificationModel model) {
        if (model.getModule() == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请输入模块名");
        }

        //最近发布的一条
        Notification notification = notificationManager.findLastByModuleWithStatus(model.getModule(), NotificationStatus.RELEASE);
        if (notification == null) {
            return null;
        }
        //是否已读
        long count = readNotificationManager.countByNotificationId(userId, notification.getId());
        if (count > 0) {
            return null;
        }

        return notification;
    }

    @Override
    public Long addNotification(Notification notification) {
        notificationValidator.validateAddNotification(notification);

        notificationManager.save(notification);
        return notification.getId();
    }

    @Override
    public Long updateNotification(Notification notification) {
        notificationValidator.validateUpdateNotification(notification);
        notificationManager.update(notification);
        return notification.getId();
    }
}
